import Request from 'luch-request'
import Vue from 'vue'
import store from '@/store/index.js'
import {
	baseUrl, build
} from '@/api/baseUrl.js'
import {
	storage
} from '@/common/utils/storage.js'
import {
	show
} from '@/common/utils/show.js'
	
import {
	router,
	toLogin
} from '@/router'
import cript from '@/common/utils/encript.js';

let timeout = 10000 //超时时长10s,
let timeoutForLoading = 500 //1000ms后加载不出来数据，显示loading,
// import qs from 'qs'
const http = new Request({
	// baseURL: baseUrl, //设置请求的base url
	// sslVerify:false,
	timeout: timeout
})

//请求拦截器
http.interceptors.request.use((config) => {
	// console.log('config', config)
	config.baseURL = baseUrl
	config.header = configHeader(config)

	if (!config.custom.noLoading) {
		setTimeout(function() {
			if (!config.custom.isResponse) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
			}
		}, timeoutForLoading)
	}
	//设置默认参数
	// if (config.method == 'GET') {
	// 	config.params = config.params ? config.params : {}
	// 	config.params['build'] = config.params.build ? config.params.build : build
	// } else if (config.method == 'POST') {
	// 	config.data = config.data ? config.data : {}
	// 	config.data['build'] = config.data.build ? config.data.build : build
	// }
	let encriptConfig = cript.encript(config);
	return encriptConfig
}, error => {
	return Promise.reject(error)
})

// 响应拦截器
http.interceptors.response.use((response) => {
	// 解密
	response = cript.decript(response)
	printMessage(response)
	if (response.statusCode === 200) {
		if(response.data.code === 10000){
			//特殊接口处理
			handleAssignApi(response)
		}else if (response.data.code === 8888) {
			uni.showToast({
				title: response.data.message,
				icon: 'none'
			})
		} else if (response.data.code === 7777) {
			uni.showModal({
				content: response.data.message,
				confirmText: '确定',
				showCancel: false
			})
		} else if (response.data.code === 401 || response.data.code === 40002) {
			handleStatusFor401(response.config.url)
			return Promise.reject(response)
		} else{
			
		}

	} else if (response.statusCode === 401) {
		handleStatusFor401(response.config.url)
		return Promise.reject(response)
	} else {
		// uni.showToast({
		// 	title: "网络异常，请稍后重试！",
		// 	icon: 'none'
		// })
	}
	return response
}, (err) => {
	uni.stopPullDownRefresh()
	printMessage(err)
	if(err.errMsg && (err.errMsg.indexOf('timeout')>-1 | err.errMsg.indexOf('请求超时')>-1)){
		// uni.showToast({
		// 	title: "网络超时，请稍后重试",
		// 	icon: 'none'
		// })
	}else if(err.statusCode == 401 || err.statusCode == 40002 || err.data.code == 40002){//token失效
		handleStatusFor401(err.config.url)
	}else {
		// uni.showToast({
		// 	title: "网络异常，请稍后重试！",
		// 	icon: 'none'
		// })
	}
	return Promise.reject(err)
})
export default http;

function configHeader(config) {
	var header = {}
	header['Content-Type'] = 'application/json'
	header["Authorization"] = 'token ' + storage.getStorageDataSync(store.state.token)
	// header["Authorization"] = 'token ' + '4502bfaf430bc4b7979a0d8762d21a5f'
	
	header["clientname"] = store.state.clientname
	header["channel"] = store.state.channel
	header["version"] = store.state.version
	header["build"] = build
	return header
}

function handleAssignApi(response){
	
}

let flag = false
function handleStatusFor401(url) {
	console.log('url', url)
	if(url.indexOf('coupon/add')>-1){ //点击领取优惠券直接跳转到登录界面
		toLogin({})
	}else{
		if (flag) {
			return
		}
		flag = true
		uni.showModal({
			content: '登录状态已失效，是否重新登录',
			confirmText: "确定",
			cancelText: "取消",
			success(res) {
				flag = false
				if (res.confirm) {
					console.log('torouth', router)
					toLogin({})
				}
			}
		})
	}
}

function printMessage(response) {
	//收到响应输出日志且关闭loading
	console.log('\n\n-----received request ' + response.config.method + ' ' + response.config.fullPath)
	if(response.config.data && response.config.data.data){
		response.config.data.data = cript.decript(response.config)
	}
	console.log('response:', response)
	console.log('-----end---------------------\n\n')
	if (!response.config.custom.noLoading) {
		response.config.custom.isResponse = true
		uni.hideLoading()
	}
}
